package com.mayikt;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: maplefire
 * @Description:
 * @Date: 2022/11/01 15:02
 */

public class Test04 implements Runnable {
    // 共享的全局变量
    // private static int count = 1;
    AtomicInteger atomicInteger = new AtomicInteger(); // 线程安全

    public void run() {
        while (true) {
            Integer count = getCount();
            if (count >= 170) {
                break;
            }
            System.out.println(count);
        }
    }

    public Integer getCount() {
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 每次自增++ 线程安全，底层没有使用锁
        return atomicInteger.incrementAndGet();
    }

    public static void main(String[] args) {
        Test04 test04 = new Test04();
        Thread t1 = new Thread(test04);
        Thread t2 = new Thread(test04);
        t1.start();
        t2.start();
    }
}
